package com.leadership.api.web.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.utils.DateFormatUtils;
import com.leadership.api.entity.SapTrainerSearch;
import com.leadership.api.entity.SapUserSearch;
import com.leadership.api.entity.TrainerAppraisalReportSearch;
import com.leadership.api.service.DataService;
import com.leadership.api.service.ReportService;
import com.leadership.api.service.TrainingSurveyResultService;
import com.leadership.training.entity.course.Course;
import com.leadership.training.entity.project.ProjectPhaseCourse;
import com.leadership.training.entity.project.ProjectTrainee;
import com.leadership.training.entity.project.TrainingSurveyResult;
import com.leadership.training.entity.report.TrainerCourseReport;

/**
 * 
 * @author mohanlan
 *
 */
@RestController
@RequestMapping("")
public class SapApiController {

    private static final Logger logger = LoggerFactory.getLogger(SapApiController.class);

    @Autowired
    @Qualifier("dataService")
    private DataService<ProjectTrainee> dataService;

    @Autowired
    @Qualifier("dataService")
    private DataService<ProjectPhaseCourse> trainerDataService;

    @Autowired
    private ReportService reportService;

    @Autowired
    private TrainingSurveyResultService trainingSurveyResultService;

    @RequestMapping(value = "/sap-user-stats", method = RequestMethod.POST,
        produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult listUsers(SapUserSearch sapUserSearch) {

        HttpResult httpResult = new HttpResult();
        try {
            List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
            List<ProjectTrainee> projectTrainees = dataService.search(ProjectTrainee.class, sapUserSearch);

            for (ProjectTrainee projectTrainee : projectTrainees) {
                Map<String, Object> params = new HashMap<String, Object>();

                params.put("PERNR", projectTrainee.getTrainee().getUsernumber());
                params.put("BEGDA", DateFormatUtils.format(projectTrainee.getCreateTime(), "yyyyMMdd"));
                params.put("ZPXXM", projectTrainee.getProject().getName());
                params.put("ZPXXMID", projectTrainee.getProject().getId().toString());
                params.put("ZBEGDA", DateFormatUtils.format(projectTrainee.getProject().getBeginDate(), "yyyyMMdd"));
                params.put("ZENDDA", DateFormatUtils.format(projectTrainee.getProject().getEndDate(), "yyyyMMdd"));
                params.put("ZSFJY",
                    projectTrainee.getComplete() == null ? "2" : (projectTrainee.getComplete() ? "1" : "2"));
                params.put("ZSFBK", projectTrainee.getResit() == null ? "2" : (projectTrainee.getResit() ? "1" : "2"));
                params.put("ZQQTS", String.valueOf(projectTrainee.getAbsence()));
                params.put("Z9126ZZCJ",
                    projectTrainee.getScore() == null ? null : String.valueOf(projectTrainee.getScore()));
                params.put("ZYXXY", projectTrainee.getGreatValue() == null ? "3"
                    : (projectTrainee.getGreatValue() == true ? "1" : "2"));
                params.put("ZMARK", projectTrainee.getComment());
                params.put("DISABLED", projectTrainee.isDisabled() ? "true" : "false");

                data.add(params);
            }

            httpResult.success().data("userStats", data).message("list sap user stat success");

        } catch (Exception e) {
            logger.error("get result error:", e);
            httpResult.fail("500").message("获取学员课程统计数据异常");
        }

        return httpResult;
    }

    /**
     *
     * @param sapTrainerSearch
     * @return
     */
    @RequestMapping(value = "/sap-coach-stats", method = RequestMethod.POST,
        produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult listCoach(SapTrainerSearch sapTrainerSearch) {
        HttpResult httpResult = new HttpResult();

        List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
        List<ProjectPhaseCourse> projectPhaseCourses =
            trainerDataService.search(ProjectPhaseCourse.class, sapTrainerSearch);

        try {

            for (ProjectPhaseCourse projectPhaseCourse : projectPhaseCourses) {

                Map<String, Object> params = new HashMap<String, Object>();
                params.put("PERNR", projectPhaseCourse.getTrainer().getCode()); // 教练编码 code
                params.put("TRAINERTYPE", "3"); // 类型 3
                params.put("ZPXXM", projectPhaseCourse.getProjectPhase().getProject().getName()); // 项目名称
                params.put("ZPXXMID", projectPhaseCourse.getProjectPhase().getProject().getId()); // 项目id
                params.put("BEGDA", DateFormatUtils
                    .format(projectPhaseCourse.getProjectPhase().getProject().getCreateTime(), "yyyyMMdd")); // 创建时间
                params.put("ZBEGDA", DateFormatUtils
                    .format(projectPhaseCourse.getProjectPhase().getProject().getBeginDate(), "yyyyMMdd")); // 开始时间
                params.put("ZENDDA",
                    DateFormatUtils.format(projectPhaseCourse.getProjectPhase().getProject().getEndDate(), "yyyyMMdd")); // 结束时间
                params.put("COURSE", projectPhaseCourse.getCourse().getName()); // 课程名称
                params.put("HOURS", projectPhaseCourse.getCourse().getHour().toString()); // 课程时长
                params.put("SCORE", projectPhaseCourse.getTrainerSurveyResult()); // 分数
                params.put("TIMES", 1); // 授课次数 1
                params.put("CERTIFICATE", projectPhaseCourse.getTrainer().getCertifiedDate() != null ? "1" : "0"); // 认证1
                                                                                                                   // ，未认证0
                params.put("DISABLED", projectPhaseCourse.isDisabled() ? "true" : "false"); // phase course ture 删除

                data.add(params);
            }

            httpResult.success().data("coachStats", data).message("list sap coach stat success");

        } catch (Exception e) {
            logger.error("get result error:", e);
            httpResult.fail("500").message("获取内训师统计数据异常");
        }

        return httpResult;
    }

    /**
     *
     * @return
     */
    @RequestMapping(value = "/sap-update-stats", method = RequestMethod.GET)
    public @ResponseBody HttpResult updateData() {
        HttpResult httpResult = new HttpResult();

        try {

            TrainerAppraisalReportSearch trainerAppraisalReportSearch = new TrainerAppraisalReportSearch();

            int totals = reportService.count(trainerAppraisalReportSearch);
            if (totals > 0) {

                @SuppressWarnings("rawtypes")
                List courseList = reportService.searchForExport(trainerAppraisalReportSearch);
                List<TrainerCourseReport> trainerCourseReportList = new ArrayList<TrainerCourseReport>();

                TrainerCourseReport trainerCourseReport = new TrainerCourseReport();
                List<TrainerCourseReport> trainerCourseReports = new ArrayList<TrainerCourseReport>();
                for (int i = 0; i < courseList.size(); i++) {
                    ProjectPhaseCourse projectPhaseCourse = (ProjectPhaseCourse)courseList.get(i);
                    Course course = projectPhaseCourse.getCourse();
                    // set survey result / suggestion to each course
                    List<TrainingSurveyResult> trainingSurveyResultList =
                        trainingSurveyResultService.listByProjectPhaseCourse(projectPhaseCourse.getId());
                    // 管理类课程分类统计用
                    // 需求匹配度
                    int xu = 0;
                    int cntXu = 0;
                    // 展示技巧
                    int zsjqs = 0;
                    int cntZsjqs = 0;
                    // 改进建议
                    String gjjys = "";
                    // 内容理解深度
                    int ljsds = 0;
                    int cntLjsds = 0;
                    // 讲师总体评分
                    int zf = 0;
                    int cntDefault = 0;
                    for (int j = 0; j < trainingSurveyResultList.size(); j++) {
                        TrainingSurveyResult tsr = trainingSurveyResultList.get(j);
                        String inputVal = tsr.getInputValue();
                        if (inputVal == null || inputVal.trim().length() < 1) {
                            // empty input continue to next
                            continue;
                        }

                        if (tsr.getKeywords() != null) {
                            // check keywords
                            if (tsr.getKeywords().contains("需求匹配")) {
                                if (!"NA".equals(inputVal)) {
                                    // int score
                                    try {
                                        xu += Integer.valueOf(inputVal);
                                        cntXu++;
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        logger.error(e.getMessage());
                                    }
                                }
                            } else if (tsr.getKeywords().contains("展示技巧")) {
                                if (!"NA".equals(inputVal)) {
                                    // int score
                                    try {
                                        zsjqs += Integer.valueOf(inputVal);
                                        cntZsjqs++;
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        logger.error(e.getMessage());
                                    }
                                }
                            } else if (tsr.getKeywords().contains("内容理解深度")) {
                                if (!"NA".equals(inputVal)) {
                                    // int score
                                    try {
                                        ljsds += Integer.valueOf(inputVal);
                                        cntLjsds++;
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        logger.error(e.getMessage());
                                    }
                                }
                            } else if (tsr.getKeywords().contains("改进建议")) {
                                if (inputVal != null && inputVal.length() > 0) {
                                    if (gjjys != null && gjjys.length() > 0) {
                                        gjjys += ";";
                                    }
                                    gjjys += inputVal;
                                }
                            }

                        } else {
                            // check key words in question body

                            if (tsr.getQuestion().contains("主题课程是否满足您的期望")) {
                                // 需求匹配度
                                if (!"NA".equals(inputVal)) {
                                    // int score
                                    try {
                                        xu += Integer.valueOf(inputVal);
                                        cntXu++;
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        logger.error(e.getMessage());
                                    }
                                }
                            } else if (tsr.getQuestion().contains("授课逻辑清晰易懂，呈现演绎生动有趣")) {
                                // 展示技巧
                                if (!"NA".equals(inputVal)) {
                                    // int score
                                    try {
                                        zsjqs += Integer.valueOf(inputVal);
                                        cntZsjqs++;
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        logger.error(e.getMessage());
                                    }
                                }
                            } else if (tsr.getQuestion().contains("对主题内容有深度的理解")) {
                                // 内容理解深度
                                if (!"NA".equals(inputVal)) {
                                    // int score
                                    try {
                                        ljsds += Integer.valueOf(inputVal);
                                        cntLjsds++;
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        logger.error(e.getMessage());
                                    }
                                }
                            } else if (tsr.getQuestion().contains("主题课程有哪些需要改进的地方")) {
                                // 改进建议
                                if (inputVal != null && inputVal.length() > 0) {
                                    if (gjjys != null && gjjys.length() > 0) {
                                        gjjys += ";";
                                    }
                                    gjjys += inputVal;
                                }
                            } else {
                                // 如果是评分值，计入总分，否则当成建议
                                try {
                                    zf += Integer.valueOf(inputVal);
                                    cntDefault++;
                                } catch (Exception e) {
                                    // not int value process as String
                                    if (inputVal != null && inputVal.length() > 0) {
                                        if (gjjys != null && gjjys.length() > 0) {
                                            gjjys += ";";
                                        }
                                        gjjys += inputVal;
                                    }
                                }
                            }
                        }
                    }
                    // 需求平均分
                    if (xu == 0 || cntXu == 0) {
                        trainerCourseReport.setPiPeiDu("0");
                    } else {
                        BigDecimal bd = new BigDecimal(xu * 1.0 / cntXu);
                        double d1 = bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        trainerCourseReport.setPiPeiDu("" + String.valueOf(d1));
                    }
                    // 展示技巧
                    if (zsjqs == 0 || cntZsjqs == 0) {
                        trainerCourseReport.setZsjq("0");
                    } else {
                        BigDecimal bd = new BigDecimal(zsjqs * 1.0 / cntZsjqs);
                        double d1 = bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        trainerCourseReport.setZsjq("" + String.valueOf(d1));
                    }
                    // 内容理解深度
                    if (ljsds == 0 || cntLjsds == 0) {
                        trainerCourseReport.setLjsd("0");
                    } else {
                        BigDecimal bd = new BigDecimal(ljsds * 1.0 / cntLjsds);
                        double d1 = bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        trainerCourseReport.setLjsd("" + String.valueOf(d1));
                    }
                    // 改进建议
                    trainerCourseReport.setGjjy(gjjys);
                    // 总体评分
                    zf += xu + zsjqs + ljsds;
                    cntDefault += cntXu + cntZsjqs + cntLjsds;

                    if (zf == 0 || cntDefault == 0) {
                        trainerCourseReport.setZf("0");
                    } else {
                        BigDecimal bd = new BigDecimal(zf * 1.0 / cntDefault);
                        double d1 = bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        trainerCourseReport.setZf("" + String.valueOf(d1));
                    }

                    // 讲师评分 =展示技巧 + 理解深度
                    if ((zsjqs + ljsds) == 0 || (cntZsjqs + cntLjsds) == 0) {
                        // 如果空值， 用总分代替
                        trainerCourseReport.setTrainerSurveyResult(trainerCourseReport.getZf());
                    } else {
                        BigDecimal bd = new BigDecimal((zsjqs + ljsds) * 1.0 / (cntZsjqs + cntLjsds));
                        double d1 = bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        trainerCourseReport.setTrainerSurveyResult("" + String.valueOf(d1));
                    }

                    // 课程评分（ =总分）
                    trainerCourseReport.setCourseSurveyResult(trainerCourseReport.getZf());

                    trainerCourseReports.add(new TrainerCourseReport(trainerCourseReport));

                    projectPhaseCourse.setCourse(course);
                    trainerCourseReportList
                        .add(new TrainerCourseReport(projectPhaseCourse, trainerCourseReports.get(i)));
                }

                trainingSurveyResultService.resultDataUpdate(trainerCourseReportList);

            }

        } catch (Exception e) {
            logger.error("#scanSurveyItems() - occur exception=[{}]", e);
        }
        return httpResult;
    }

}
